package cn.com.surker.lab.controller;

import cn.com.surker.common.AbstractController;
import cn.com.surker.lab.entity.LabLevelConstruct;
import cn.com.surker.lab.entity.LabLevelConstructMaterial;
import cn.com.surker.lab.entity.LabLevelOptimize;
import cn.com.surker.lab.entity.LabLevelOptimizeMaterial;
import cn.com.surker.lab.service.LabLevelConstructMaterialService;
import cn.com.surker.lab.service.LabLevelConstructService;
import cn.com.surker.lab.service.LabLevelOptimizeMaterialService;
import cn.com.surker.lab.service.LabLevelOptimizeService;
import cn.com.surker.spring.RestResultDto;
import cn.com.surker.system.model.CacheUser;
import cn.com.surker.util.StringUtils;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.transaction.RollbackException;
import java.util.List;

/**
 * @Author lucky
 * @create 2024年10月16 20:37
 * @desc 标准配合比控制类
 */
@RestController
@RequestMapping("/lab/level-optimize")
public class LabLevelOptimizeController extends AbstractController {

    @Resource
    private LabLevelOptimizeService levelOptimizeService;
    @Resource
    private LabLevelOptimizeMaterialService levelOptimizeMaterialService;
    @Value("${erp.org.id}")
    protected String erpOrgId;

    /**
     * 分页查询施工配合比
     * @param searchVal
     * @param strengthId
     * @param status
     * @param page
     * @param limit
     * @param curr
     * @return
     */
    @RequestMapping(value = "/page", method = RequestMethod.POST)
    @ResponseBody
    public RestResultDto page(String searchVal, Long strengthId, Integer status, Integer page, Integer limit, Integer curr) {
        try {
            /**分页对象**/
            if (!StringUtils.isNull(curr))//layui不能用page传页码数则修改默认页码参数传入
                page = curr;
            else {
                if (StringUtils.isNull(page))
                    page = 1;
            }
            if (StringUtils.isNull(page))
                page = 1;
            if (StringUtils.isNull(limit))
                limit = 15;
            IPage iPage = levelOptimizeService.findPage(searchVal, strengthId, status, (page - 1) * limit, limit);
                return RestResultDto.success(iPage);
        } catch (Exception e) {
            e.printStackTrace();
            return RestResultDto.fail(e.getMessage());
        }
    }

    /**
     * 查询施工配合比材料列表
     * @param levelConstructId
     * @return
     */
    @RequestMapping(value = "/find-material", method = RequestMethod.POST)
    @ResponseBody
    public RestResultDto findMaterial(Long levelConstructId) {
        try {
            List<LabLevelOptimizeMaterial> list = levelOptimizeMaterialService.findByConstruct(levelConstructId);
            if (list == null)
                return RestResultDto.fail("未获取到材料数据");
            return RestResultDto.success(list);
        } catch (Exception e) {
            e.printStackTrace();
            return RestResultDto.fail(e.getMessage());
        }
    }

    /**
     * 保存施工配合比
     * @param levelConstruct
     * @param results
     * @return
     */
    @RequestMapping(value = "/save", method = RequestMethod.PUT)
    @ResponseBody
    @Transactional(rollbackFor = RollbackException.class, propagation = Propagation.REQUIRED)
    public RestResultDto save(@Validated @RequestBody LabLevelOptimize levelConstruct, BindingResult results) {
        try {
            if (results.hasErrors()) {
                String defaultMessage = results.getFieldError().getDefaultMessage();
                return RestResultDto.fail(defaultMessage);
            }
            if (levelConstruct.getList() == null || levelConstruct.getList().size() == 0)
                return RestResultDto.fail("配合比材料子项不能为空");
            List<LabLevelOptimizeMaterial> list = levelConstruct.getList();
            CacheUser user = getUser();
            levelConstruct.setCreator(user.getName());
            RestResultDto dto = levelOptimizeService.saveLevel(levelConstruct);
            if (dto.getCode() != 0)
                return dto;
            LabLevelOptimize construct = (LabLevelOptimize) dto.getData();

            return levelOptimizeMaterialService.saveBatchConstructMaterial(construct, list);
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            e.printStackTrace();
            return RestResultDto.fail(e.getMessage());
        }
    }
    /**
     * 保存施工配合比
     * @param levelConstruct
     * @return
     */
    @RequestMapping(value = "/update", method = RequestMethod.PUT)
    @ResponseBody
    public RestResultDto update(@Validated @RequestBody LabLevelOptimize levelConstruct, BindingResult results) {
        try {
            if (results.hasErrors()) {
                String defaultMessage = results.getFieldError().getDefaultMessage();
                return RestResultDto.fail(defaultMessage);
            }
            CacheUser user = getUser();
            levelConstruct.setUpdator(user.getName());
            RestResultDto dto = levelOptimizeService.updateLevel(levelConstruct);
            if (dto.getCode() != 0)
                return dto;
            if (levelConstruct.getList() == null || levelConstruct.getList().size() == 0) {
                    return dto;
            } else {
                LabLevelOptimize construct = (LabLevelOptimize) dto.getData();

                return levelOptimizeMaterialService.saveBatchConstructMaterial(construct, levelConstruct.getList());
            }
        } catch (Exception e) {
            e.printStackTrace();
            return RestResultDto.fail(e.getMessage());
        }
    }
    /**
     * 修改施工配合比状态
     * @return
     */
    @RequestMapping(value = "/update-status/{id}", method = RequestMethod.PUT)
    @ResponseBody
    public RestResultDto updateStatus(@PathVariable Long id, Integer status, String remark) {
        try {
            CacheUser user = getUser();

            return levelOptimizeService.updateStatus(id, status, remark, user.getName());
        } catch (Exception e) {
            e.printStackTrace();
            return RestResultDto.fail(e.getMessage());
        }
    }

    /**
     * 保存施工配合比
     * @param levelConstruct
     * @param results
     * @return
     */
    @RequestMapping(value = "/save-material", method = RequestMethod.PUT)
    @Transactional(rollbackFor = RollbackException.class, propagation = Propagation.REQUIRED)
    public RestResultDto save(@Validated LabLevelOptimizeMaterial levelConstruct, BindingResult results) {
        try {
            if (results.hasErrors()) {
                String defaultMessage = results.getFieldError().getDefaultMessage();
                return RestResultDto.fail(defaultMessage);
            }
            CacheUser user = getUser();
            levelConstruct.setCreator(user.getName());

            return levelOptimizeMaterialService.saveConstructMaterial(levelConstruct);
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            e.printStackTrace();
            return RestResultDto.fail(e.getMessage());
        }
    }
    /**
     * 保存施工配合比
     * @param levelConstruct
     * @return
     */
    @RequestMapping(value = "/update-material", method = RequestMethod.PUT)
    public RestResultDto updateMaterial(LabLevelOptimizeMaterial levelConstruct) {
        try {
            CacheUser user = getUser();
            levelConstruct.setUpdator(user.getName());

            return levelOptimizeMaterialService.updateConstructMaterial(levelConstruct);
        } catch (Exception e) {
            e.printStackTrace();
            return RestResultDto.fail(e.getMessage());
        }
    }
    /**
     * 修改施工配合比状态
     * @return
     */
    @RequestMapping(value = "/update-material-status", method = RequestMethod.PUT)
    public RestResultDto updateMaterialStatus(Long id, Integer status, String remark) {
        try {
            CacheUser user = getUser();

            return levelOptimizeMaterialService.updateStatus(id, status, remark, user.getName());
        } catch (Exception e) {
            e.printStackTrace();
            return RestResultDto.fail(e.getMessage());
        }
    }

    /**
     * 解析Excel文件
     * @param enclosureId
     * @return
     */
    @RequestMapping(value = "/analysis", method = RequestMethod.POST)
    @Transactional(rollbackFor = RollbackException.class, propagation = Propagation.REQUIRED)
    public RestResultDto analysis(Long enclosureId) {
        try {
            CacheUser user = getUser();
            Long orgId = null;
            if (!StringUtils.isNull(erpOrgId))
                orgId = StringUtils.convertLong(erpOrgId);
            return levelOptimizeService.analysisOptimize(orgId, enclosureId, user.getName());
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            e.printStackTrace();
            return RestResultDto.fail(e.getMessage());
        }
    }

}
